package wang.xinqiu.mysqlcontrol.data

import android.content.Context
import android.content.SharedPreferences

class UserPreferences(context: Context) {
    private val prefs: SharedPreferences = context.getSharedPreferences("user_preferences", Context.MODE_PRIVATE)
    
    // 主题设置
    var isDarkMode: Boolean
        get() = prefs.getBoolean("dark_mode", false)
        set(value) = prefs.edit().putBoolean("dark_mode", value).apply()
    
    // 查询设置
    var queryTimeout: Int
        get() = prefs.getInt("query_timeout", 30)
        set(value) = prefs.edit().putInt("query_timeout", value).apply()
    
    var autoSaveQueries: Boolean
        get() = prefs.getBoolean("auto_save_queries", true)
        set(value) = prefs.edit().putBoolean("auto_save_queries", value).apply()
    
    var maxHistorySize: Int
        get() = prefs.getInt("max_history_size", 100)
        set(value) = prefs.edit().putInt("max_history_size", value).apply()
    
    // 显示设置
    var showLineNumbers: Boolean
        get() = prefs.getBoolean("show_line_numbers", true)
        set(value) = prefs.edit().putBoolean("show_line_numbers", value).apply()
    
    var fontSize: Float
        get() = prefs.getFloat("font_size", 14f)
        set(value) = prefs.edit().putFloat("font_size", value).apply()
    
    var enableSyntaxHighlight: Boolean
        get() = prefs.getBoolean("syntax_highlight", true)
        set(value) = prefs.edit().putBoolean("syntax_highlight", value).apply()
    
    // 连接设置
    var autoReconnect: Boolean
        get() = prefs.getBoolean("auto_reconnect", true)
        set(value) = prefs.edit().putBoolean("auto_reconnect", value).apply()
    
    var connectionTimeout: Int
        get() = prefs.getInt("connection_timeout", 10)
        set(value) = prefs.edit().putInt("connection_timeout", value).apply()
    
    var maxConnections: Int
        get() = prefs.getInt("max_connections", 3)
        set(value) = prefs.edit().putInt("max_connections", value).apply()
    
    // 性能设置
    var enableQueryCache: Boolean
        get() = prefs.getBoolean("enable_query_cache", true)
        set(value) = prefs.edit().putBoolean("enable_query_cache", value).apply()
    
    var cacheTimeout: Int
        get() = prefs.getInt("cache_timeout", 5)
        set(value) = prefs.edit().putInt("cache_timeout", value).apply()
    
    var enablePerformanceMonitor: Boolean
        get() = prefs.getBoolean("performance_monitor", true)
        set(value) = prefs.edit().putBoolean("performance_monitor", value).apply()
    
    // 导出设置
    var defaultExportFormat: String
        get() = prefs.getString("default_export_format", "CSV") ?: "CSV"
        set(value) = prefs.edit().putString("default_export_format", value).apply()
    
    var includeHeaders: Boolean
        get() = prefs.getBoolean("include_headers", true)
        set(value) = prefs.edit().putBoolean("include_headers", value).apply()
    
    // 安全设置
    var rememberPasswords: Boolean
        get() = prefs.getBoolean("remember_passwords", true)
        set(value) = prefs.edit().putBoolean("remember_passwords", value).apply()
    
    var sessionTimeout: Int
        get() = prefs.getInt("session_timeout", 30)
        set(value) = prefs.edit().putInt("session_timeout", value).apply()
    
    // 获取所有设置的摘要
    fun getSettingsSummary(): Map<String, Any> {
        return mapOf(
            "主题模式" to if (isDarkMode) "深色" else "浅色",
            "查询超时" to "${queryTimeout}秒",
            "自动保存查询" to if (autoSaveQueries) "开启" else "关闭",
            "历史记录数量" to "${maxHistorySize}条",
            "字体大小" to "${fontSize}sp",
            "语法高亮" to if (enableSyntaxHighlight) "开启" else "关闭",
            "自动重连" to if (autoReconnect) "开启" else "关闭",
            "连接超时" to "${connectionTimeout}秒",
            "查询缓存" to if (enableQueryCache) "开启" else "关闭",
            "性能监控" to if (enablePerformanceMonitor) "开启" else "关闭",
            "默认导出格式" to defaultExportFormat,
            "记住密码" to if (rememberPasswords) "开启" else "关闭"
        )
    }
    
    // 重置所有设置为默认值
    fun resetToDefaults() {
        prefs.edit().clear().apply()
    }
    
    // 导出设置
    fun exportSettings(): String {
        val allPrefs = prefs.all
        return allPrefs.entries.joinToString("\n") { "${it.key}=${it.value}" }
    }
    
    // 导入设置
    fun importSettings(settingsString: String): Boolean {
        return try {
            val editor = prefs.edit()
            settingsString.lines().forEach { line ->
                if (line.contains("=")) {
                    val (key, value) = line.split("=", limit = 2)
                    when {
                        value == "true" || value == "false" -> editor.putBoolean(key, value.toBoolean())
                        value.toIntOrNull() != null -> editor.putInt(key, value.toInt())
                        value.toFloatOrNull() != null -> editor.putFloat(key, value.toFloat())
                        else -> editor.putString(key, value)
                    }
                }
            }
            editor.apply()
            true
        } catch (e: Exception) {
            false
        }
    }
}